package com.idlecode.panel;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.TableEditor;
import org.eclipse.swt.events.ControlAdapter;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.StrUtil;

import com.idlecode.bean.DataBaseEntity;
import com.idlecode.bean.DataSourceEntity;
import com.idlecode.bean.TableEntity;
import com.idlecode.component.MultipleSelectionCombo;
import com.idlecode.config.GenDataSource;
import com.idlecode.service.DataBaseService;
import com.idlecode.service.DataSourceService;
import com.idlecode.service.GeneratorService;
import com.idlecode.service.TableService;
import com.idlecode.statics.TemplateInfoStatic;
import com.idlecode.util.MessageDialogUtil;

public class CodeGenerationPanel extends Composite {
	private Table table;
	private Combo dataSourceComboBox;
	private Combo dataBaseComboBox;
	private Text tableNameField;
	private Button syncBtn;
	private Button refreshDataSourceBtn;
	private Button initGenRadioBtn;
	private Button updateBaseCodeRadioBtn;
	private Button updateAllCodeRadioBtn;
	private Button genBtn;
	private Button apiFormatcheckBox;
	private MultipleSelectionCombo codeFileComboBox;

	private static List<TableEntity> tableList;
	private static List<DataBaseEntity> dataBaseList;

	private TableColumn tableNameColumn;
	private TableColumn CommentCommentColumn;

	private final static String spacer_1 = " ";
	private final static String spacer_10 = "         ";

	public CodeGenerationPanel(Composite parent, int style) {
		super(parent, style);

		initializeComponents();
		addEventListeners();

		boolean showDataBases = showDataBases();
		if (!showDataBases) {
			MessageDialogUtil.showError("异常", "数据库连接失败！");
		}
	}

	/**
	 * 控件初始化...
	 */
	private void initializeComponents() {
		setLayout(new GridLayout(1, false));
		Composite topComposite = new Composite(this, SWT.NONE);
		RowLayout rowLayout = new RowLayout(SWT.HORIZONTAL);
		rowLayout.wrap = true; // 自动换行
		rowLayout.center = true; // 垂直居中对齐
//		rowLayout.pack = false; // 不自动调整控件大小
//		rowLayout.justify = false; // 不调整控件间距使其对齐
		topComposite.setLayout(rowLayout);
		topComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));

		// 数据源标签
		Label dataSourceLabel = new Label(topComposite, SWT.NONE);
		dataSourceLabel.setText("数据源：");

		// 数据源下拉框
		String[] dataSourceNames = getDataSourceNames();// 获取数据源
		dataSourceComboBox = new Combo(topComposite, SWT.DROP_DOWN | SWT.READ_ONLY);// 生成数据源下拉框
		RowData dataSourceComboBoxRowData = new RowData();
		dataSourceComboBoxRowData.width = 125; // 设置宽度
		dataSourceComboBox.setLayoutData(dataSourceComboBoxRowData);
		dataSourceComboBox.setItems(dataSourceNames); // 设置数据源下拉框数据
		dataSourceComboBox.select(0);// 默认选中第一项

		// 添加空白组件
		new Label(topComposite, SWT.NONE).setText(spacer_1);// 空白组件不显示文本，用于设置组件距离

		// 数据库标签
		Label dataBaseLabel = new Label(topComposite, SWT.NONE);
		dataBaseLabel.setText("数据库：");

		// 数据库下拉框
		dataBaseComboBox = new Combo(topComposite, SWT.DROP_DOWN | SWT.READ_ONLY);
		RowData dataBaseComboBoxRowData = new RowData();
		dataBaseComboBoxRowData.width = 125; // 设置宽度
		dataBaseComboBox.setLayoutData(dataBaseComboBoxRowData);

		// 添加空白组件
		new Label(topComposite, SWT.NONE).setText(spacer_1);// 空白组件不显示文本，用于设置组件距离

		// 刷新数据源按钮
		refreshDataSourceBtn = new Button(topComposite, SWT.PUSH);
		refreshDataSourceBtn.setText("刷新数据源");

		// 添加空白组件
		new Label(topComposite, SWT.NONE).setText(spacer_1);// 空白组件不显示文本，用于设置组件距离

		// 表名或者表注释搜索框
		tableNameField = new Text(topComposite, SWT.BORDER);
		RowData tableNameFieldRowData = new RowData();
		tableNameFieldRowData.width = 125; // 设置宽度
		tableNameField.setLayoutData(tableNameFieldRowData);
		tableNameField.setText("请输入表名或注释");
		tableNameField.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_GRAY)); // 设置提示文本颜色为灰色

		// 添加空白组件
		new Label(topComposite, SWT.NONE).setText(spacer_1);// 空白组件不显示文本，用于设置组件距离

		// 同步表按钮
		syncBtn = new Button(topComposite, SWT.PUSH);
		syncBtn.setText("同步表");

		// 添加空白组件
		new Label(topComposite, SWT.NONE).setText(spacer_1);// 空白组件不显示文本，用于设置组件距离

		// 生成文件类型下拉框
		codeFileComboBox = new MultipleSelectionCombo(topComposite, TemplateInfoStatic.TemplateInfoNames, SWT.BORDER);
		RowData codeFileComboBoxRowData = new RowData();
		codeFileComboBoxRowData.width = 125; // 设置宽度
		codeFileComboBox.setLayoutData(codeFileComboBoxRowData);
		codeFileComboBox.setSelectedItems(TemplateInfoStatic.TemplateInfoNames);

		// 添加空白组件
		new Label(topComposite, SWT.NONE).setText(spacer_1);// 空白组件不显示文本，用于设置组件距离

		// 初始化单选按钮
		initGenRadioBtn = new Button(topComposite, SWT.RADIO);
		initGenRadioBtn.setText("初始化");
		initGenRadioBtn.setToolTipText("初始化代码会生成所有代码文件");
		initGenRadioBtn.setSelection(true);

		// 更新基础代码单选按钮
		updateBaseCodeRadioBtn = new Button(topComposite, SWT.RADIO);
		updateBaseCodeRadioBtn.setText("更新基础代码");
		updateBaseCodeRadioBtn.setToolTipText("只更新BaseEntity.java和BaseMapper.xml");

		// 更新完整代码单选按钮
		updateAllCodeRadioBtn = new Button(topComposite, SWT.RADIO);
		updateAllCodeRadioBtn.setText("更新完整代码");
		updateAllCodeRadioBtn.setToolTipText("更新BaseEntity.java、BaseMapper.xml、Mapper.xml");

		// 添加竖直分割线
		Label verticalSeparator = new Label(topComposite, SWT.SEPARATOR | SWT.VERTICAL | SWT.SHADOW_OUT);
		RowData verticalSeparatorRowData = new RowData();
		verticalSeparatorRowData.width = 12; // 设置宽度
		verticalSeparatorRowData.height = 15;
		verticalSeparator.setLayoutData(verticalSeparatorRowData);

		// 创建复选按钮
		apiFormatcheckBox = new Button(topComposite, SWT.CHECK);
		apiFormatcheckBox.setText("Api异常格式化");
		apiFormatcheckBox.setToolTipText("选中此项，则生成的controller接口异常会改成 ==> res.error(e)");

		// 添加空白组件
		new Label(topComposite, SWT.NONE).setText(spacer_10);// 空白组件不显示文本，用于设置组件距离

		// 生成代码按钮
		genBtn = new Button(topComposite, SWT.PUSH);
		genBtn.setText("生成代码");
		genBtn.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_GREEN));// 设置按钮的背景颜色

		// 列表显示
		Composite bottomComposite = new Composite(this, SWT.NONE);
		bottomComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
		bottomComposite.setLayout(new FillLayout());

		table = new Table(bottomComposite, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI);
		table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
		table.setHeaderVisible(true);
		table.setLinesVisible(true);

		tableNameColumn = new TableColumn(table, SWT.NONE);
		tableNameColumn.setText("表名");
		tableNameColumn.setWidth(100);
		tableNameColumn.pack();

		CommentCommentColumn = new TableColumn(table, SWT.NONE);
		CommentCommentColumn.setText("注释");
		CommentCommentColumn.setWidth(100);
		CommentCommentColumn.pack();
	}

	/**
	 * 控件事件监听...
	 */
	private void addEventListeners() {
		// 数据源下拉框添加选择监听器
		dataSourceComboBox.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				boolean showDataBases = showDataBases();
				if (!showDataBases) {
					MessageDialogUtil.showError("提示", "数据库连接失败！");
				}
			}
		});

		// 数据库下拉框添加选择监听器
		dataBaseComboBox.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				 int selectionIndex = dataBaseComboBox.getSelectionIndex();
		            if (selectionIndex >= 0) {
		            	if (!refreshTable()) {
							MessageDialogUtil.showError("提示", "数据库连接失败！");
						}
		            }
				
			}
		});

		// 刷新数据源按钮点击事件监听器
		refreshDataSourceBtn.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				String[] finalDataSourceNames = getDataSourceNames();
				if (finalDataSourceNames != null && finalDataSourceNames.length > 0) {
					dataSourceComboBox.setItems(finalDataSourceNames);
					// 默认选中第一项
					dataSourceComboBox.select(0);
				}
				boolean showDataBases = showDataBases();
				if (showDataBases) {
					MessageDialogUtil.showMessage("提示", "数据源刷新成功！");
				} else {
					MessageDialogUtil.showWarning("提示", "数据源刷新成功！,但数据库连接失败！");
				}
			}
		});

		// 表名搜索框事件监听器
		tableNameField.addModifyListener(new ModifyListener() {
			@Override
			public void modifyText(ModifyEvent arg0) {
				table.removeAll();
				String text = tableNameField.getText();
				if (CharSequenceUtil.isNotBlank(text) && !"请输入表名或注释".equals(text)) {
					if (CollUtil.isNotEmpty(tableList)) {
						String textLowerCase = text.toLowerCase();
						List<TableEntity> filterTable = tableList.stream()
								.filter(tableEntity -> (StrUtil.isBlank(tableEntity.getTableName()) ? false
										: tableEntity.getTableName().toLowerCase().contains(textLowerCase))
										|| (StrUtil.isBlank(tableEntity.getTableComment()) ? false
												: tableEntity.getTableComment().toLowerCase().contains(textLowerCase)))
								.collect(Collectors.toList());
						// 添加数据到表格中
						for (TableEntity tableEntity : filterTable) {
							TableItem item = new TableItem(table, SWT.NONE);
							item.setText(new String[] { tableEntity.getTableName(), tableEntity.getTableComment() });
						}
					}
				} else {
					if (CollUtil.isNotEmpty(tableList)) {
						table.removeAll();
						// 添加数据到表格中
						for (TableEntity tableEntity : tableList) {
							TableItem item = new TableItem(table, SWT.NONE);
							item.setText(new String[] { tableEntity.getTableName(), tableEntity.getTableComment() });
						}
					}
				}

			}
		});

		// 表名搜索框焦点事件监听器
		tableNameField.addFocusListener(new FocusAdapter() {
			// 当 Text 控件获得焦点时触发的事件处理逻辑
			@Override
			public void focusGained(FocusEvent e) {
				if (tableNameField.getText().contains("请输入表名或注释")) {
					tableNameField.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_BLACK));
					tableNameField.setText("");
				}
			}

			// 当 Text 控件失去焦点时触发的事件处理逻辑
			@Override
			public void focusLost(FocusEvent e) {
				if (CharSequenceUtil.isBlank(tableNameField.getText())) {
					// 设置 Text 中文字的颜色为灰色
					tableNameField.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_GRAY));
					tableNameField.setText("请输入表名或注释");
				}
			}
		});

		// 表同步按钮添加按钮点击事件监听器
		syncBtn.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				if (refreshTable()) {
					MessageDialogUtil.showMessage("提示", "表同步成功！");
				} else {
					MessageDialogUtil.showError("异常", "数据库连接失败!");
				}
			}
		});

		// 初始化生成代码添加选择监听器
		initGenRadioBtn.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				codeFileComboBox.setSelectedItems(TemplateInfoStatic.TemplateInfoNames);
			}
		});

		// 更新基础代码添加选择监听器
		updateBaseCodeRadioBtn.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				String[] selectedOptions = new String[] { "BaseEntity.java", "BaseMapper.xml" };
				codeFileComboBox.setSelectedItems(selectedOptions);
			}
		});

		// 更新完整代码添加选择监听器
		updateAllCodeRadioBtn.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				String[] selectedOptions = new String[] { "BaseEntity.java", "BaseMapper.xml", "Mapper.xml" };
				codeFileComboBox.setSelectedItems(selectedOptions);
			}
		});

		// 生成代码按钮添加按钮点击事件监听器
		genBtn.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				IProject project = getSelectedProject();
				if (project == null) {
					MessageDialogUtil.showWarning("警告", "您未选择任何项目，请选择项目后重试!");
					return;
				}
				boolean isProject = isProject(project);
				if (!isProject) {
					MessageDialogUtil.showWarning("警告", "您选中的不是项目，请选择项目后重试!");
					return;
				}
				boolean open = project.isOpen();
				if (!open) {
					MessageDialogUtil.showWarning("警告", "您选中的项目已关闭，请打开项目后重试!");
					return;
				}
				// 获取选中的行
				TableItem[] selectedTableItems = table.getSelection();
				if (selectedTableItems == null || selectedTableItems.length <= 0) {
					MessageDialogUtil.showWarning("警告", "未选中任何表！");
					return;
				}
				// 通过选中行索引获取该行数据
				List<String> tableNames = new ArrayList<>();
				for (TableItem selectedTableItem : selectedTableItems) {
					String tableName = selectedTableItem.getText(0);
					tableNames.add(tableName);
				}
				// 获取选中的数据源
				int dataSourceSelectedIndex = dataSourceComboBox.getSelectionIndex();
				if (dataSourceSelectedIndex < 0) {
					MessageDialogUtil.showWarning("警告", "未选中任何数据源！");
					return;
				}
				DataSourceEntity dataSourceEntity = DataSourceService.getDataSources().get(dataSourceSelectedIndex);

				// 获取选择的数据库的项的索引
				int dataBaseSelectedIndex = dataBaseComboBox.getSelectionIndex();
				if (dataBaseSelectedIndex < 0) {
					MessageDialogUtil.showWarning("警告", "未选中任何数据库！");
					return;
				}
				// 获取选择的数据库的项的文本
				String dataBaseSelectedItem = dataBaseComboBox.getItem(dataBaseSelectedIndex);

				List<String> selectedGenFileItems = codeFileComboBox.getSelectedItems();
				if (CollUtil.isEmpty(selectedGenFileItems)) {
					MessageDialogUtil.showWarning("警告", "未选中生成文件类型！");
					return;
				}

				try {
					GeneratorService.generateCode(project, dataSourceEntity, tableNames, dataBaseSelectedItem,
							selectedGenFileItems, apiFormatcheckBox.getSelection());

					// 刷新项目
					project.refreshLocal(IProject.DEPTH_INFINITE, null);
					MessageDialogUtil.showMessage("提示", "代码生成成功！");
					// VCS 刷新
					// VcsUtil.refreshVcs(project);
				} catch (Exception ex) {
					MessageDialogUtil.showError("警告", ex.getMessage());
				}

			}
		});

		// 添加一个监听器，在表格调整大小时动态调整列宽
		table.addControlListener(new ControlAdapter() {
			@Override
			public void controlResized(ControlEvent e) {
				int tableWidth = table.getClientArea().width;
				tableNameColumn.setWidth((int) (tableWidth * 0.5));
				CommentCommentColumn.setWidth((int) (tableWidth * 0.5));
			}
		});

		// 添加双击事件监听器
		table.addListener(SWT.MouseDoubleClick, event -> {
			Point point = new Point(event.x, event.y);
			TableItem item = table.getItem(point);
			if (item != null) {
				int columnIndex = -1;
				for (int i = 0; i < table.getColumnCount(); i++) {
					Rectangle bounds = item.getBounds(i);
					if (bounds.contains(point)) {
						columnIndex = i;
						break;
					}
				}
				if (columnIndex != -1) {
					final TableEditor editor = new TableEditor(table);
					// 设置编辑器的数据输入控件
					Text text = new Text(table, SWT.NONE);
					text.setText(item.getText(columnIndex));
					// 设置编辑器与选定单元格关联
					editor.grabHorizontal = true;
					editor.setEditor(text, item, columnIndex);
					// 添加焦点丢失监听器，实现编辑完成后的处理
					text.addFocusListener(new FocusAdapter() {
						public void focusLost(FocusEvent event) {
							item.setText(text.getText());
							text.dispose();
							editor.dispose();
						}
					});
					// 设置输入框焦点，启动编辑模式
					text.setFocus();
					// 将鼠标焦点放在文本的最后面
					text.setSelection(text.getText().length());
				}
			}
		});
	}

	/**
	 * 获取数据库
	 *
	 * @return
	 */
	public boolean showDataBases() {
		// 清除表格中的额数据
		table.removeAll();
		// 清除数据库名下拉框
		dataBaseComboBox.removeAll();
		// 获取所有数据源
		List<DataSourceEntity> dataSourcesRows = DataSourceService.getDataSources();
		if (CollUtil.isNotEmpty(dataSourcesRows)) {
			// 获取选中的数据源
			int dataSourceSelectedIndex = dataSourceComboBox.getSelectionIndex();
			DataSourceEntity dataSourceEntity = dataSourcesRows.get(dataSourceSelectedIndex);
			GenDataSource genDataSource = null;
			try {
				genDataSource = new GenDataSource(dataSourceEntity);
				if (genDataSource.getConnection() == null) {
					return false;
				}
				dataBaseList = DataBaseService.getDataBaseList(genDataSource);
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					if (genDataSource.getConnection() != null) {
						genDataSource.getConnection().close();
					}
				} catch (SQLException ex) {
					MessageDialogUtil.showError("异常", "连接关闭失败！");
				}
			}

			for (DataBaseEntity dataBaseEntity : dataBaseList) {
				dataBaseComboBox.add(dataBaseEntity.getOwner());
			}
		}
		return true;
	}

	/**
	 * 刷新表格
	 *
	 * @return
	 */
	public boolean refreshTable() {
		// 清除表格中的额数据
		table.removeAll();
		List<DataSourceEntity> dataSourcesRows = DataSourceService.getDataSources();
		if (CollUtil.isNotEmpty(dataSourcesRows)) {
			// 获取选择的数据源
			int dataSourceSelectedIndex = dataSourceComboBox.getSelectionIndex();
			DataSourceEntity dataSourceEntity = dataSourcesRows.get(dataSourceSelectedIndex);
			GenDataSource genDataSource = null;
			try {
				// 获取选择的数据库的项的索引
				int dataBaseSelectedIndex = dataBaseComboBox.getSelectionIndex();
				// 获取选择的数据库的项的文本
				String dataBaseSelectedItem = dataBaseComboBox.getItem(dataBaseSelectedIndex);
				genDataSource = new GenDataSource(dataSourceEntity, dataBaseSelectedItem);
				if (genDataSource.getConnection() == null) {
					return false;
				}
				
				if (CharSequenceUtil.isNotBlank(dataBaseSelectedItem)) {
					tableList = TableService.getTableList(genDataSource, dataBaseSelectedItem);
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					if (genDataSource.getConnection() != null) {
						genDataSource.getConnection().close();
					}
				} catch (SQLException ex) {
					MessageDialogUtil.showError("异常", "连接关闭失败！");
				}
			}

			String text = tableNameField.getText();
			if (CharSequenceUtil.isNotBlank(text) && !"请输入表名或注释".equals(text)) {
				if (CollUtil.isNotEmpty(tableList)) {
					String textLowerCase = text.toLowerCase();
					List<TableEntity> filterTable = tableList.stream()
							.filter(tableEntity -> (StrUtil.isBlank(tableEntity.getTableName()) ? false
									: tableEntity.getTableName().toLowerCase().contains(textLowerCase))
									|| (StrUtil.isBlank(tableEntity.getTableComment()) ? false
											: tableEntity.getTableComment().toLowerCase().contains(textLowerCase)))
							.collect(Collectors.toList());
					// 添加数据到表格中
					for (TableEntity tableEntity : filterTable) {
						TableItem item = new TableItem(table, SWT.NONE);
						item.setText(new String[] { tableEntity.getTableName(), tableEntity.getTableComment() });
					}
				}
			} else {

				// 添加数据到表格中
				for (TableEntity tableEntity : tableList) {
					TableItem item = new TableItem(table, SWT.NONE);
					item.setText(new String[] { tableEntity.getTableName(), tableEntity.getTableComment() });
				}
			}
		}
		return true;
	}

	/**
	 * 获取数据源
	 */
	private static String[] getDataSourceNames() {
		List<DataSourceEntity> dataSources = DataSourceService.getDataSources();
		String[] options = null;
		if (dataSources != null) {
			List<String> connNames = dataSources.stream().map(DataSourceEntity::getConnName)
					.collect(Collectors.toList());
			options = connNames.toArray(new String[0]);
		}
		return options;
	}

	public static IProject getSelectedProject() {
		IProject projectByProjectExplorer = getSelectedProjectByProjectExplorer();
		if (projectByProjectExplorer != null) {
			return projectByProjectExplorer;
		}
		return getSelectedProjectByPackageExplorer();
	}

	/**
	 * 从ProjectExplorer视图中获取选中的项目
	 * 
	 * @return
	 */
	public static IProject getSelectedProjectByProjectExplorer() {
		IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
		if (window != null) {
			// 明确指定从 Project Explorer 获取选中项
			ISelection selection = window.getSelectionService()
					.getSelection("org.eclipse.ui.navigator.ProjectExplorer");
			if (selection instanceof IStructuredSelection) {
				Object firstElement = ((IStructuredSelection) selection).getFirstElement();
				if (firstElement instanceof IProject) {
					return (IProject) firstElement;
				} else if (firstElement instanceof IResource) {
					return ((IResource) firstElement).getProject();
				} else if (firstElement instanceof IJavaElement) {
					IJavaProject javaProject = ((IJavaElement) firstElement).getJavaProject();
					return javaProject.getProject();
				}
			}
		}
		return null;
	}

	/**
	 * 从PackageExplorer视图中获取选中的项目
	 * 
	 * @return IProject
	 */
	public static IProject getSelectedProjectByPackageExplorer() {
		IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
		if (window != null) {
			// 明确指定从 Package Explorer 获取选中项
			ISelection selection = window.getSelectionService().getSelection("org.eclipse.jdt.ui.PackageExplorer");
			if (selection instanceof IStructuredSelection) {
				Object firstElement = ((IStructuredSelection) selection).getFirstElement();
				if (firstElement instanceof IProject) {
					return (IProject) firstElement;
				} else if (firstElement instanceof IResource) {
					return ((IResource) firstElement).getProject();
				} else if (firstElement instanceof IJavaElement) {
					IJavaProject javaProject = ((IJavaElement) firstElement).getJavaProject();
					return javaProject.getProject();
				}
			}
		}
		return null;
	}

	/**
	 * 判断是否是项目
	 * 
	 * @param resource
	 * @return
	 */
	public static boolean isProject(IResource resource) {
		return resource instanceof IProject;
	}
}